# -*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from process_bar import ProgressBar
import sys
import time

key_words = [u'面膜', u'洗面奶', u'花露水', u'化妆棉', u'眼霜', u'杏仁', u'饼干', u'薯片', u'麦片', u'牛肉干', u'巧克力', u'红酒',
             u'伏特加', u'金酒', u'茅台', u'啤酒', u'牛奶', u'鸡蛋', u'猪肋骨', u'鱼', u'土鸡', u'牛排', u'苹果', u'橙子', u'速冻水饺',
             u'NFC果汁', u'玉米油', u'米', u'盐', u'糖', u'酱油', u'醋', u'卷纸', u'抽纸', u'沐浴露', u'洗发水', u'洗洁精', u'洗衣粉',
             u'香皂', u'保鲜膜', u'保鲜袋', u'卫生巾', u'牙膏', u'牙刷', u'毛巾']
file_out = None


def search_key_word(driver, key_word, index):
    global file_out
    try:
        elem_close = driver.find_element_by_class_name('J_MIDDLEWARE_FRAME_WIDGET')
        print 'close', elem_close.text
        item_close = elem_close.find_element_by_tag_name('a')
        print item_close.text
        item_close.click()
    except Exception, e:
        pass

    print key_word
    process_bar = None
    elem_search = driver.find_element_by_name('q')
    elem_search.clear()
    elem_search.send_keys(key_word)
    elem_search.send_keys(Keys.RETURN)
    while True:
        try:
            elem_close = driver.find_element_by_class_name('J_MIDDLEWARE_FRAME_WIDGET')
            print 'close', elem_close.text
            item_close = elem_close.find_element_by_tag_name('a')
            print item_close.text
            item_close.click()
        except Exception, e:
            pass
        if driver.title == u'理想生活上天猫':
            iframe = driver.find_element_by_tag_name('iframe')
            driver.switch_to_frame(iframe)
            elem_switch = driver.find_element_by_class_name('login-switch')
            elem_switch.click()
            elem_name = driver.find_element_by_name('TPL_username')
            elem_name.clear()
            elem_name.send_keys(u'xxx')
            elem_password = driver.find_element_by_name('TPL_password')
            elem_password.clear()
            elem_password.send_keys('xxx')
            elem_login = driver.find_element_by_id('J_SubmitStatic')
            elem_login.click()
            driver.implicitly_wait(2)
        elif u'天猫超市-天猫Tmall.com-上天猫，就购了-理想生活上天猫' not in driver.title:
            wait = WebDriverWait(driver, 3600 * 24)
            element = driver.find_element_by_tag_name('div')
            ActionChains(driver).context_click(element).perform()
            elem = wait.until(EC.title_contains(u'天猫超市-天猫Tmall.com-上天猫，就购了-理想生活上天猫'))
        else:
            try:
                elem_list = driver.find_element_by_id('J_ProductList')
                elem_products = elem_list.find_elements_by_class_name('product')
            except Exception, e:
                break
            for elem_product in elem_products:
                try:
                    sku_id = elem_product.get_attribute('data-itemid')
                    file_out.write(','.join([key_word, str(sku_id), str(index)]) + '\n')
                    print [key_word, str(sku_id), str(index)]
                except Exception, e:
                    print e.message
                    print elem_product.get_attribute('data-itemid')
            # time.sleep(3)
            try:
                elem_quick_page_changer = driver.find_element_by_class_name('quick-page-changer')
                elem_page_info = elem_quick_page_changer.find_element_by_tag_name('span').text.split('/')
                if len(elem_page_info) == 2:
                    if process_bar is None:
                        process_bar = ProgressBar(count=int(elem_page_info[0]), total=int(elem_page_info[1]))
                    else:
                        process_bar.move()
                    print '\n'
                    process_bar.log()
                    print '\n'
                    if elem_page_info[0] == elem_page_info[1]:
                        break
                elif len(elem_page_info) == 1:
                    break
                elem = driver.find_element_by_class_name('page-next')
                try:
                    elem.click()
                except Exception, e:
                    wait = WebDriverWait(driver, 3600 * 24)
                    ActionChains(driver).context_click(elem).perform()
                    wait.until(EC.element_to_be_clickable(elem))
                    elem.click()
            except Exception, e:
                break


if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('gbk')
    file_out = open('../data/ID_TMALL_SUPERMARKET.csv', 'w')

    init_driver = webdriver.Chrome()
    init_driver.get('https://chaoshi.tmall.com/')
    init_driver.maximize_window()
    for index, key in enumerate(key_words):
        search_key_word(init_driver, key, index)
    init_driver.quit()
    file_out.close()
